package com.yykj.common.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.Date;

public class JsonUtil {

    private static Gson gson;

    public static Gson getInstance(){
        if(gson == null){
            GsonBuilder builder = new GsonBuilder();
//            builder.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
//            builder.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);

            gson = builder.create();
        }
        return gson;
    }

    public static String toJson(Object obj) {
        return getInstance().toJson(obj);
    }

    public static JsonObject fromJson(String jsonStr){
        return getInstance().fromJson(jsonStr, JsonObject.class);
    }

    public static <T> T fromJson(String json,Class<T> clazz) {
        return getInstance().fromJson(json, clazz);
    }

    public static String toKeyValueJson(String... params){
        if(null == params){
            return null;
        }
        JsonObject jsonObject = new JsonObject();
        int len = params.length;
        for(int i = 0; i < len; i +=2 ){
            if(i+1 < len){
                jsonObject.addProperty(params[i],params[i+1]);
            }
        }
        return getInstance().toJson(jsonObject);
    }


    public static  <T> T  fromJson(String json, Type type){
        return getInstance().fromJson(json, type);
    }

}
